//
//  AssetsParser.swift
//  JKTool
//
//  Created by liuyan on 2023/5/29.
//

import Foundation

struct AssetsParser {
    func parseContent(path: String) -> [String: UInt]? {
        let fileManager = FileManager.default
        
        guard fileManager.fileExists(atPath: path) else {
            po(tip: "请选择正确的Assets文件路径", type: .error)
            return nil
        }
        
        let outputPath = "assetsInfo.json"
        if fileManager.fileExists(atPath: outputPath) {
            do {
                try fileManager.removeItem(atPath: outputPath)
            } catch {
                po(tip: "清理文件失败\r\n\(error)", type: .error)
                return nil
            }
        }
        
        do {
            try shellOut(to: ShellOutCommand(string: "xcrun --sdk iphoneos assetutil --info \(path) > \(outputPath)"))
        } catch  {
            let error = error as! ShellOutError
            po(tip: "AssetsParse" + error.message + error.output, type: .error)
            return nil
        }
        
        do {
            let fileContent = try String(contentsOfFile: outputPath)
            if let jsonData = fileContent.data(using: .utf8),
               let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]] {
                var sizeMap = [String: UInt]()
                for info in jsonObject {
                    if let name = info["Name"] as? String {
                        if let size = info["SizeOnDisk"] as? UInt {
                            sizeMap[name] = size + (sizeMap[name] ?? 0)
                        }
                    }
                }
                return sizeMap
            }
        } catch {
            po(tip: "读取文件失败：\r\n\(error)", type: .error)
            return nil
        }
        
        return nil
    }
}
